package cn.buk.tms.dto;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * PAT:a 结果
 * @author yfdai
 */
public class PatInfo {

    private final List<PatItem> items = new ArrayList<>();

    public static PatInfo createByPatResponse(final String patResponse) {
        if(!patResponse.contains("PAT:A")) {
          return null;
        }

        PatInfo info = new PatInfo();

        final String regExp1 = "^[0-9]{2} [A-Z0-9/+]{1,30} FARE:CNY[0-9.]{4,8} TAX:((CNY[0-9.]{4,8})|(TEXEMPTCN)) YQ:((CNY[0-9.]{4,8})|(TEXEMPTYQ))[ ]{1,4}TOTAL:[0-9.]{4,8}";
        // 多行模式，匹配行首和行尾
        final Pattern p1 = Pattern.compile(regExp1, Pattern.MULTILINE);
        Matcher m1 = p1.matcher(patResponse);
        while(m1.find()) {
            String strLine = patResponse.substring(m1.start(), m1.end());

            String[] items = strLine.split("[ ]+");

            PatItem patItem = new PatItem();
            info.items.add(patItem);

            patItem.setItemNo(items[0]);
            patItem.setFareBasis(items[1]);

            patItem.setFare(Float.parseFloat(items[2].substring(8)));
            if (!items[3].contains("TEXEMPTCN")) {
                patItem.setTax(Float.parseFloat(items[3].substring(7)));
            }
            if(!items[4].contains("TEXEMPTYQ")) {
                patItem.setOilFee(Float.parseFloat(items[4].substring(6)));
            }
            patItem.setTotal(Float.parseFloat(items[5].substring(6)));
        }

        return info;
    }

    public int getCount() {
        return items.size();
    }

    public PatItem getItemByIndex(int index) {
        return items.get(index);
    }
}
